import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  OnInit,
} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {NzMessageService} from "ng-zorro-antd/message";
import {ValidatorsService} from "../../../../core/services/validators/validators.service";
import {fnCheckForm} from "../../../../utils/tools";
import {MsdsHttpService} from "../../../../core/services/http/msds/msds-enterprise.service";
import {MsdsIdService} from "../../../../core/services/store/biz-store-service/msds-id/msds-id.service";
import {NzUploadFile} from "ng-zorro-antd/upload";
import {environment} from "../../../../../environments/environment.prod";
import {AdminService} from "../../../../core/services/store/admin.service";


@Component({
  selector: 'app-msds-enterprise',
  templateUrl: './msds-enterprise.component.html',
  styleUrls: ['./msds-enterprise.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MsdsEnterpriseComponent implements OnInit {
  validateForm!: FormGroup;
  formOrder = 1;
  id!: number;
  uploadUrl: string;
  showUploadList = {
    showPreviewIcon: true,
    showRemoveIcon: true,
    hidePreviewIconInNonImage: true,
  };
  previewImage: string | undefined = '';
  previewVisible = false;
  fileList: any[] = [];

  constructor(private fb: FormBuilder, private msg: NzMessageService,
              private validatorsService: ValidatorsService,
              private cdr: ChangeDetectorRef,
              private msdsIdService: MsdsIdService, public AdminService: AdminService,
              private dataService: MsdsHttpService) {
    this.uploadUrl = environment.production ? '/api/file/upload/picture' : '/api/file/upload/picture';
  }


  initForm(): void {
    this.validateForm = this.fb.group({
      cnName: [null, [Validators.required]],
      enName: [null],
      formula: [null],
      entprName: [null],
      entprAddress: [null],
      construction: [null],
      entprFax: [null],
      effectDate: [null],
      entprPhone: [null, [this.validatorsService.allPhoneValidator()]],
      countryEmergentPhone: [null, [this.validatorsService.allPhoneValidator()]],
      entprEmergentPhone: [null, [this.validatorsService.allPhoneValidator()]],
    });
  }

  submitForm(): void {
    if (!fnCheckForm(this.validateForm)) {
      return;
    }
    const params = this.validateForm.value;
    if (this.id === -1) {
      this.dataService.addMsds(this.validateForm.value).subscribe((res) => {
        this.msdsIdService.setMsdsIdStore(res);
        this.cdr.markForCheck();
      });
    } else {
      params.id = this.id;
      this.dataService.editMsds(params).subscribe(() => {
      })
    }
  }

  handlePreview(file: NzUploadFile): void {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }

  handleRemove(file: NzUploadFile): boolean {
    // @ts-ignore
    this.validateForm.get('construction').setValue(null);
    this.validateForm.updateValueAndValidity();
    return true;
  }

  uploadFn(e: any): void {
    if (e.type === 'success') {
      if (e.file.response.code === 0) {
        this.validateForm.get('construction')!.setValue(e.file.response.data);
      }
    }
  }

  getDetail(id: number): void {
    this.dataService.getMsdsDetail(id).subscribe(res => {
      if (res.construction !== null) {
        this.fileList = [{
          url: res.construction,
        }];
      }
      this.validateForm.patchValue(res);
    })
  }

  ngOnInit(): void {
    this.initForm();
    this.msdsIdService.getMsdsIdStoreStore().subscribe(res => this.id = res);
    if (this.id !== -1) {
      this.getDetail(this.id);
    }
  }

}
